package appapi.controller.mqtt;

import appapi.common.ResponseBean;
import appapi.entity.DeviceDataEntity;
import appapi.entity.mqtt.TopicReq;
import appapi.service.DeviceDataService;
import appapi.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @version: java version 1.8
 * @Author: Ygp Work
 * @description:
 * @date: 2024-03-18 17:42
 */
@RestController
@RequestMapping("/device/data")
public class DeviceDataController {

    @Autowired
    private RedisUtils redisUtils;

    @CrossOrigin
    @ApiOperation(value = "实时数据获取")
    @GetMapping("/realDataList")
    public ResponseBean getValueFromRedis(TopicReq req) {
        String key = "real_data_" + req.getDeviceImei();
        Object value = redisUtils.get(key);
        if (value != null) {
            return ResponseBean.success(value);
        } else {
            return ResponseBean.fail("没有查到这台设备的数据");
        }
    }

    @CrossOrigin
    @ApiOperation(value = "告警实时数据获取")
    @GetMapping("/realAlarmDataList")
    public ResponseBean getAlarmValueFromRedis(TopicReq req) {
        String key = "real_alarm_" + req.getDeviceImei();
        Object value = redisUtils.get(key);
        if (value != null) {
            return ResponseBean.success(value);
        } else {
            return ResponseBean.fail("没有查到这台设备的数据");
        }
    }

    @Autowired
    private DeviceDataService deviceDataService;

    @PostMapping("/add")
    @CrossOrigin
    public ResponseBean addDeviceData(@RequestBody DeviceDataEntity deviceDataEntity) {
        boolean success = deviceDataService.save(deviceDataEntity);
        if (success) {
            //将设备添加进表中进行订阅
            return ResponseBean.success("添加成功");
        } else {
            return ResponseBean.fail("添加失败");
        }
    }
}
